import React, { useState } from 'react';
import {
  Table,
  Card,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Avatar,
  Typography,
  Modal,
  Form,
  message,
  Popconfirm,
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title } = Typography;
const { Option } = Select;

interface User {
  key: string;
  id: number;
  nickname: string;
  avatarUrl?: string;
  college: string;
  grade: string;
  creditPoints: number;
  uploadCount: number;
  downloadCount: number;
  status: 'active' | 'disabled';
  createdAt: string;
}

const UserManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedCollege, setSelectedCollege] = useState<string>('');
  const [selectedStatus, setSelectedStatus] = useState<string>('');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  // 模拟数据
  const [users, setUsers] = useState<User[]>([
    {
      key: '1',
      id: 1,
      nickname: '张三',
      college: '计算机科学与技术学院',
      grade: '2024',
      creditPoints: 1250,
      uploadCount: 15,
      downloadCount: 45,
      status: 'active',
      createdAt: '2024-01-10 10:30:00',
    },
    {
      key: '2',
      id: 2,
      nickname: '李四',
      college: '理学院',
      grade: '2023',
      creditPoints: 980,
      uploadCount: 12,
      downloadCount: 38,
      status: 'active',
      createdAt: '2024-01-08 15:20:00',
    },
    {
      key: '3',
      id: 3,
      nickname: '王五',
      college: '材料科学与工程学院',
      grade: '2024',
      creditPoints: 856,
      uploadCount: 10,
      downloadCount: 25,
      status: 'disabled',
      createdAt: '2024-01-05 09:15:00',
    },
  ]);

  const colleges = [
    '计算机科学与技术学院',
    '信息工程学院',
    '材料科学与工程学院',
    '理学院',
    '经济管理学院',
    '外国语学院',
  ];

  const columns: ColumnsType<User> = [
    {
      title: '用户信息',
      key: 'userInfo',
      render: (_, record) => (
        <Space>
          <Avatar
            src={record.avatarUrl}
            icon={<UserOutlined />}
            size="large"
          />
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.nickname}</div>
            <div style={{ color: '#666', fontSize: '12px' }}>ID: {record.id}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '学院',
      dataIndex: 'college',
      key: 'college',
    },
    {
      title: '年级',
      dataIndex: 'grade',
      key: 'grade',
    },
    {
      title: '学力值',
      dataIndex: 'creditPoints',
      key: 'creditPoints',
      render: (points: number) => (
        <span style={{ color: '#1890ff', fontWeight: 'bold' }}>{points}</span>
      ),
      sorter: (a, b) => a.creditPoints - b.creditPoints,
    },
    {
      title: '上传/下载',
      key: 'activity',
      render: (_, record) => (
        <div>
          <div>上传: {record.uploadCount}</div>
          <div>下载: {record.downloadCount}</div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      sorter: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title={`确定要${record.status === 'active' ? '禁用' : '启用'}该用户吗？`}
            onConfirm={() => handleToggleStatus(record)}
          >
            <Button type="link">
              {record.status === 'active' ? '禁用' : '启用'}
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleEdit = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setModalVisible(true);
  };

  const handleToggleStatus = (user: User) => {
    const newStatus = user.status === 'active' ? 'disabled' : 'active';
    setUsers(users.map(u => 
      u.id === user.id ? { ...u, status: newStatus } : u
    ));
    message.success(`用户${newStatus === 'active' ? '启用' : '禁用'}成功`);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingUser) {
        // 更新用户
        setUsers(users.map(u => 
          u.id === editingUser.id ? { ...u, ...values } : u
        ));
        message.success('用户信息更新成功');
      }
      setModalVisible(false);
      setEditingUser(null);
      form.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModalCancel = () => {
    setModalVisible(false);
    setEditingUser(null);
    form.resetFields();
  };

  // 过滤数据
  const filteredUsers = users.filter(user => {
    const matchesSearch = user.nickname.toLowerCase().includes(searchText.toLowerCase()) ||
                         user.college.toLowerCase().includes(searchText.toLowerCase());
    const matchesCollege = !selectedCollege || user.college === selectedCollege;
    const matchesStatus = !selectedStatus || user.status === selectedStatus;
    
    return matchesSearch && matchesCollege && matchesStatus;
  });

  return (
    <div>
      <Title level={2}>用户管理</Title>
      
      <Card>
        {/* 搜索和筛选 */}
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            <Input
              placeholder="搜索用户名或学院"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 200 }}
            />
            <Select
              placeholder="选择学院"
              value={selectedCollege}
              onChange={setSelectedCollege}
              style={{ width: 200 }}
              allowClear
            >
              {colleges.map(college => (
                <Option key={college} value={college}>{college}</Option>
              ))}
            </Select>
            <Select
              placeholder="选择状态"
              value={selectedStatus}
              onChange={setSelectedStatus}
              style={{ width: 120 }}
              allowClear
            >
              <Option value="active">正常</Option>
              <Option value="disabled">禁用</Option>
            </Select>
          </Space>
        </div>

        {/* 用户表格 */}
        <Table
          columns={columns}
          dataSource={filteredUsers}
          loading={loading}
          pagination={{
            total: filteredUsers.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 编辑用户模态框 */}
      <Modal
        title="编辑用户信息"
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="nickname"
            label="用户昵称"
            rules={[{ required: true, message: '请输入用户昵称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="college"
            label="所属学院"
            rules={[{ required: true, message: '请选择所属学院' }]}
          >
            <Select>
              {colleges.map(college => (
                <Option key={college} value={college}>{college}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="grade"
            label="年级"
            rules={[{ required: true, message: '请输入年级' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="creditPoints"
            label="学力值"
            rules={[{ required: true, message: '请输入学力值' }]}
          >
            <Input type="number" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;
